<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      label-width="120px"
    >
      <el-form-item label="考评库名称" prop="provinceId">
        <el-select
          v-model="queryParams.name"
          placeholder="请选择考评库名称"
          filterable
          clearable
          @change="changeKpk"
          style="width: 400px"
        >
          <el-option
            v-for="item in optionData"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item>
                <el-button type="primary" @click="handleQuery">搜索</el-button>
                <el-button @click="resetQuery">重置</el-button>
            </el-form-item> -->
    </el-form>

    <div class="totalButton">
      <span class="totalPoints">总分值:{{ score }}</span>
      <div class="top-right-btn">
        <el-button type="primary" @click="handleAdd">新建</el-button>
        <el-button type="primary" @click="handleDelete" v-if="isUse !== 1"
          >删除</el-button
        >
      </div>
    </div>
    <el-form ref="ruleForm" :model="form" :rules="rules" label-width="120px">
      <el-table
        v-loading="loading"
        :data="form.dataList"
        border
        class="borderTable"
        :span-method="objectSpanMethod"
      >
        <el-table-column label="一级指标名称" align="center" prop="index1Id">
          <template #default="scope">
            <el-form-item
              v-show="scope.row.show"
              label=""
              :prop="`dataList.${scope.$index}.index1Name`"
              label-width="0px"
              :rules="rules.index1Name"
            >
              <el-input v-model="scope.row.index1Name" placeholder="请输入">
                <template #suffix v-if="scope.row.index1Name">
                  <el-icon
                    color="var(--el-color-primary)"
                    @click="handleAdd2(scope.row, scope.$index)"
                    ><Plus
                  /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <span v-show="!scope.row.show">{{ scope.row.index1Name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="分值" align="center" prop="index1Id" width="60">
          <template #default="scope">
            <!-- <el-form-item
              v-show="scope.row.show"
              label=""
              :prop="`dataList.${scope.$index}.index1Score`"
              label-width="0px"
              :rules="rules.index1Score"
            >
              <el-input v-model="scope.row.index1Score" placeholder="请输入">
              </el-input>
            </el-form-item> -->
            <span v-show="scope.row.show">{{ scopeFirst(scope.row, 1) }}</span>
            <span v-show="!scope.row.show">{{ scope.row.index1Score }}</span>
          </template>
        </el-table-column>
        <el-table-column label="二级指标名称" align="center" prop="index2Id">
          <template #default="scope">
            <el-form-item
              v-show="scope.row.show"
              label=""
              :prop="`dataList.${scope.$index}.index2Name`"
              label-width="0px"
              :rules="rules.index2Name"
            >
              <el-input v-model="scope.row.index2Name" placeholder="请输入">
                <template #suffix v-if="scope.row.index2Name">
                  <el-icon
                    color="var(--el-color-primary)"
                    @click="handleAdd3(scope.row, scope.$index)"
                    ><Plus
                  /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <span v-show="!scope.row.show">{{ scope.row.index2Name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="分值" align="center" prop="index2Id" width="60">
          <template #default="scope">
            <span v-show="scope.row.show">{{ scopeFirst(scope.row, 2) }}</span>
            <span v-show="!scope.row.show">{{ scope.row.index2Score }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="三级指标名称"
          align="center"
          prop="index3Kpi3dId"
          show-overflow-tooltip
        >
          <template #default="scope">
            <el-form-item
              v-show="scope.row.show"
              label=""
              :prop="`dataList.${scope.$index}.index3Kpi3dId`"
              label-width="0px"
              :rules="rules.index3Kpi3dId"
            >
              <el-input
                v-model="scope.row.index3Kpi3dId"
                placeholder="请输入"
                readonly
                @click="openThree(scope.row, scope.$index)"
              />
            </el-form-item>
            <span v-show="!scope.row.show">{{
              scope.row.kpIndex3Data.name
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="分值" align="center" prop="index3Id" width="90">
          <template #default="scope">
            <el-form-item
              v-show="scope.row.show"
              label=""
              :prop="`dataList.${scope.$index}.index3Score`"
              label-width="0px"
              :rules="rules.index3Score"
            >
              <el-input v-model="scope.row.index3Score" placeholder="请输入" />
            </el-form-item>
            <span v-show="!scope.row.show">{{ scope.row.index3Score }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="系统评分"
          align="center"
          prop="isSystem"
          width="90"
        >
          <template #default="scope">
            <span v-show="scope.row.show">
              <span v-if="scope.row.isSystem == '0'">否</span>
              <span v-if="scope.row.isSystem == '1'">是</span>
            </span>

            <span v-show="!scope.row.show">
              <span v-if="scope.row.kpIndex3Data.isSystem == '0'">否</span>
              <span v-if="scope.row.kpIndex3Data.isSystem == '1'">是</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="指标内容"
          align="center"
          prop="remark"
          show-overflow-tooltip
          width="300"
        >
          <template #default="scope">
            <span v-show="scope.row.show">{{ scope.row.remark }}</span>
            <span v-show="!scope.row.show">{{
              scope.row.kpIndex3Data.remark
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="评分标准"
          align="center"
          prop="index3Standard"
          width="300"
        >
          <template #default="scope">
            <el-form-item v-show="scope.row.show" label="" label-width="0px">
              <el-input
                v-model="scope.row.index3Standard"
                placeholder="请输入"
              />
            </el-form-item>
            <span v-show="!scope.row.show">{{ scope.row.index3Standard }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
          v-if="isUse !== 1"
        >
          <template #default="scope">
            <el-button
              type="text"
              v-if="scope.row.index3Id == '' || scope.row.show == true"
              @click="handleApply(scope.row)"
              >应用</el-button
            >
            <el-button
              type="text"
              v-if="scope.row.index3Id !== '' && scope.row.show == false"
              @click="handleUpdate(scope.row, score.$index)"
              >修改</el-button
            >
            <el-button
              type="text"
              @click="handleDeleteRow(scope.row, score.$index)"
              >删除</el-button
            >
            <el-button
              type="text"
              @click="handleChooseData(scope.row)"
              v-if="scope.row.kpIndex3Data.code == '26'&&scope.row.index3Id !== ''&&scope.row.show == false"
              >数据选择</el-button
            >
          </template>
        </el-table-column>
        <template #append v-if="isUse !== 1">
          <el-icon
            :size="25"
            color="var(--el-color-primary)"
            style="font-weight: bold; margin: 10px auto"
            @click="handleAddRows"
            ><Plus
          /></el-icon>
        </template>
      </el-table>
    </el-form>
    <el-dialog
      title="选择三级指标"
      v-model="open"
      width="1200px"
      append-to-body
    >
      <ThreeLevelIndexList
        :dialogVisible="open"
        @getSelection="getSelection"
        v-if="open == true"
        :tableChooseVal="tableChooseVal"
        ref="threeLevelRef"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormSelect">确定</el-button>
          <el-button plain @click="open = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      title="数据选择"
      v-model="dataChooseOpen"
      width="800px"
      append-to-body
    >
      <el-checkbox
        :indeterminate="isIndeterminate"
        v-model="checkAll"
        @change="handleCheckAllChange"
        >全部选择</el-checkbox
      >
      <el-checkbox v-model="checkNo" @change="handleCheckCancel"
        >全部取消</el-checkbox
      >
      <div style="margin: 15px 0"></div>
      <el-checkbox-group
        v-model="checkedCities"
        @change="handleCheckedCitiesChange"
      >
        <el-checkbox v-for="(v, i) in cities" :label="v.code" :key="i">{{
          v.label
        }}</el-checkbox>
      </el-checkbox-group>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitDataChoose">保存</el-button>
          <el-button plain @click="closeDataChoose">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="appraisalDatabaseManage">
import {
  getAllAppraisal,
  getAppraisal,
  applyIndexList,
  deleteIndexByIdList,
  deleteKpkList,
  getPtgxType,
  updatePtgxType,
} from "@/api/workEvaluation/evaluationStandardSetup/appraisalDatabaseManage.js";
import { dataMethod } from "@/utils/spanTable.js";
import ThreeLevelIndexList from "../Components/threeLevelIndexList";
import { onMounted } from "vue";
import { useRouter } from "vue-router";
const { proxy } = getCurrentInstance();
import { v4, v1 } from "uuid";
const router = useRouter();
const score = ref(0);
const open = ref(false);
const ind = ref();
const selectObj = ref({});
const loading = ref(false);
const isUse = ref(1);
const chooseVal = ref();
const tableChooseVal = ref();
const cityOptions = ref([]);
const checkAll = ref(false);
const checkNo = ref(false);
const isIndeterminate = ref(true);
const checkedCities = ref([]);
const cities = ref([]);
const dataChooseOpen = ref(false);
const form = ref({
  kesdName: "",
  id: "",
  dataList: [],
});
const queryParams = ref({
  kesdId: "",
});
const optionData = ref([]);
const spanObj = ref();
const positiveInteger = (rule, value, callback) => {
  const reg = /^[1-9][0-9]*$/;
  if (!value) {
    return callback(new Error("请输入三级分值"));
  } else if (isNaN(value)) {
    return callback(new Error("请输入[0,+∞）的整数"));
  } else if (!reg.test(value)) {
    callback(new Error("请输入[0,+∞）的整数"));
  } else {
    callback();
  }
};

const validatorOne = (rule, value, callback) => {
  if (!value) {
    return callback(new Error("请输入一级指标分值"));
  }
  const reg = /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g;
  if (!reg.test(value)) {
    callback(new Error("只能输入数字"));
  }
  callback();
};
const validatorTwo = (rule, value, callback) => {
  if (!value) {
    return callback(new Error("请输入二级指标分值"));
  }
  const reg = /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g;
  if (!reg.test(value)) {
    callback(new Error("只能输入数字"));
  }
  callback();
};
const rules = ref({
  kesdName: [{ required: true, message: "请输入考评库名称", trigger: "blur" }],
  index1Name: [
    { required: true, message: "请输入一级指标名称", trigger: "blur" },
  ],
  index1Score: [{ require: true, trigger: "blur", validator: validatorOne }],
  index2Name: [
    { required: true, message: "请输入二级指标名称", trigger: "blur" },
  ],
  index2Score: [{ require: true, trigger: "blur", validator: validatorTwo }],
  index3Kpi3dId: [
    { required: true, message: "请输入三级指标名称", trigger: "change" },
  ],
  index3Score: [
    { required: true, trigger: "blur", validator: positiveInteger },
  ],
});
// 计算一级指标分值和
const scopeFirst = (row, num) => {
  if (num == 1) {
    if (row.score) {
      return row.score;
    }
    let scoreArr = form.value.dataList.filter(
      (item) => item.index1Id == row.index1Id
    );
    if (scoreArr) {
      return scoreArr.reduce((prev, cur) => prev + Number(cur.index3Score), 0);
    } else {
      return 0;
    }
  } else if (num == 2) {
    if (row.score2) {
      return row.score2;
    }
    let score2Arr = form.value.dataList.filter(
      (item) => item.index2Id == row.index2Id
    );
    if (score2Arr) {
      return score2Arr.reduce((prev, cur) => prev + Number(cur.index3Score), 0);
    } else {
      return 0;
    }
  }
};
// 合并列
function objectSpanMethod({ row, column, rowIndex, columnIndex }) {
  //判断合并列
  const _row = spanObj.value[column.property]
    ? spanObj.value[column.property][rowIndex]
    : 1;
  const _col = _row > 0 ? 1 : 0;
  return {
    rowspan: _row,
    colspan: _col,
  };
}

watch(
  () => form.value.dataList,
  (val) => {
    spanObj.value = dataMethod(form.value.dataList, [
      "index1Id",
      "index2Id",
      "flag",
    ]);
    if (val.length > 0) {
      score.value = val
        .filter((item) => !item.flag)
        .reduce((prev, cur) => prev + Number(cur.index3Score), 0);
    } else {
      score.value = 0;
    }
  },
  { deep: true, immediate: true }
);

const getList = () => {
  loading.value = true;
  getAppraisal(queryParams.value).then((response) => {
    if (response.data) {
      response.data.forEach((v, i) => {
        if (v.kpIndex3Data !== null) {
          v.index3Kpi3dId = v.kpIndex3Data.name;
          v.name3Id = v.kpIndex3Data.id;
          v.isSystem = v.kpIndex3Data.isSystem;
          v.remark = v.kpIndex3Data.remark;
        }
      });
    }
    form.value.dataList = response.data;
    loading.value = false;
  });
  spanObj.value = dataMethod(form.value.dataList, [
    "index1Id",
    "index2Id",
    "flag",
  ]);
};
//表格添加行
const handleAddRows = () => {
  let newUuid = v4();
  newUuid = newUuid.replace(/[-]/g, "");
  let newUuids = v1();
  newUuids = newUuids.replace(/[-]/g, "");
  form.value.dataList.push({
    index1Id: newUuid,
    index1Name: "",
    index1Score: null,
    index2Name: "",
    index2Score: null,
    index2Id: newUuids,
    index3Id: "",
    index3Score: null,
    index3Standard: "",
    index3Kpi3dId: "",
    remark: "",
    isSystem: "",
    kpIndex3Data: {},
    ptgxTypeCodes: "",
    show: true,
  });
};
// 新增二级
const handleAdd2 = (row, index) => {
  let newUuids = v1();
  newUuids = newUuids.replace(/[-]/g, "");
  const num = form.value.dataList.filter(
    (item) => item.index1Id == row.index1Id
  ).length;
  form.value.dataList.splice(index + num, 0, {
    index1Id: row.index1Id,
    index1Name: row.index1Name,
    index1Score: row.index1Score,
    index2Name: "",
    index2Score: null,
    index2Id: newUuids,
    index3Id: "",
    remark: "",
    isSystem: "",
    index3Kpi3dId: "",
    index3Score: null,
    index3Standard: "",
    kpIndex3Data: {},
    ptgxTypeCodes: "",
    show: true,
  });
};

// 新增三级
const handleAdd3 = (row, index) => {
  const num = form.value.dataList.filter(
    (item) => item.index1Id == row.index1Id && item.index2Id == row.index2Id
  ).length;
  form.value.dataList.splice(index + num, 0, {
    index1Id: row.index1Id,
    index1Name: row.index1Name,
    index1Score: row.index1Score,
    index2Name: row.index2Name,
    index2Score: row.index2Score,
    index2Id: row.index2Id,
    index3Id: "",
    index3Kpi3dId: "",
    index3Score: null,
    index3Standard: "",
    kpIndex3Data: {},
    show: true,
    ptgxTypeCodes: "",
    remark: "",
    isSystem: "",
  });
};
// 选择三级
const openThree = (row, index) => {
  tableChooseVal.value = row;
  open.value = true;
  ind.value = index;
};
const getSelection = (val) => {
  if (val[0]) {
    if (JSON.parse(JSON.stringify(val[0])).code == "26") {
      selectObj.value = JSON.parse(JSON.stringify(val[0]));
      console.log(checkAll.value)
      console.log(checkedCities.value)
      if (tableChooseVal.value.kpIndex3Data.id) {
        let arr = [];
        arr = tableChooseVal.value.ptgxTypeCodes.split(",");
        checkedCities.value = arr;
      } else {
        checkedCities.value = [];
      }
      chooseData();
    } else {
      selectObj.value = JSON.parse(JSON.stringify(val[0]));
    }
  }
};
// 数据选择
function handleChooseData(val) {
  if(val){
    chooseVal.value = val;
    let arr = [];
    if (val.ptgxTypeCodes) {
      arr = val.ptgxTypeCodes.split(",");
    }

    checkedCities.value = arr;
  }else{
    checkedCities.value=[]
  }
  
  dataChooseOpen.value = true;
  getdataList();
}
// 全选
function handleCheckAllChange(val) {
  checkedCities.value = val ? cityOptions.value : [];
  isIndeterminate.value = false;
  checkNo.value = false;
}
// 取消全选
function handleCheckCancel() {
  checkedCities.value = [];
  isIndeterminate.value = false;
  checkAll.value = false;
}
// 反选
function handleCheckedCitiesChange(value) {
  let checkedCount = value.length;
  checkAll.value = checkedCount === cities.value.length;
  isIndeterminate.value =
    checkedCount > 0 && checkedCount < cities.value.length;
}
function chooseData() {
  dataChooseOpen.value = true;
  getdataList();
}
// 数据选择保存
const submitDataChoose = () => {
  if (chooseVal.value !== undefined) {
    let str = "";
    str = checkedCities.value.toString("");
    chooseVal.value.ptgxTypeCodes = str;
    updatePtgxType({ ...chooseVal.value }).then((res) => {
      if (res.code == 200) {
        proxy.$modal.msgSuccess("数据选择修改成功");
        dataChooseOpen.value = false;
        getList();
      }
    });
  } else {
    closeDataChoose()
  }
};
// 关闭数据选择模态框
const closeDataChoose=()=>{
  dataChooseOpen.value = false;
    checkAll.value=false
    isIndeterminate.value = true;
    checkNo.value = false;
}
// 查询平台数据更新
const getdataList = () => {
  getPtgxType().then((res) => {
    cities.value = [];
    res.data.forEach((v, i) => {
      cities.value.push({
        label: v.dictItemName,
        code: v.dictItemCode,
      });
      cityOptions.value.push(v.dictItemCode);
    });
  });
};
const submitFormSelect = () => {
  console.log(checkedCities.value)
  let str = checkedCities.value.toString();
  nextTick(() => {
    if (JSON.stringify(selectObj.value) != "{}") {
      const obj = selectObj.value;
      tableChooseVal.value = selectObj.value;
      form.value.dataList[ind.value].kpIndex3Data = obj
      form.value.dataList[ind.value].index3Kpi3dId = obj.name;
      form.value.dataList[ind.value].name3Id = obj.id;
      form.value.dataList[ind.value].remark = obj.remark;
      form.value.dataList[ind.value].isSystem = obj.isSystem;
      form.value.dataList[ind.value].ptgxTypeCodes = str;
      open.value = false;
    }
  });
};
// 添加按钮
const handleAdd = () => {
  router.push({
    path: "/workEvaluation/evaluationStandardSetup/addEvaluation",
    query: {
      metaTitle: "新建考评库",
    },
  });
};
//应用
const handleApply = (val) => {
  proxy.$refs["ruleForm"].validate((valid) => {
    if (valid) {
      let arr = [];
      form.value.dataList.forEach((v, i) => {
        if (v.index3Id == "" || v.index3Id == null) {
          v.index3Kpi3dId = v.name3Id;
          arr.push(v);
        } else {
          v.index3Kpi3dId = v.kpIndex3Data.id;
          arr.push(v);
        }
      });

      const data = {
        kesdName: queryParams.value.name,
        kesdId: queryParams.value.kesdId,
        indexList: arr,
      };
      applyIndexList(data).then((res) => {
        proxy.$modal.msgSuccess("保存成功");
        getList();
      });
    } else {
      console.log("error submit!!");
      return false;
    }
  });
};
const handleUpdate = (val) => {
  form.value.dataList.forEach((v, i) => {
    if (v.index1Id == val.index1Id) {
      v.show = true;
    }
  });
  // console.log(val)
  // val.show = true;
  // val.index3Kpi3dId = val.kpIndex3Data.name;
  // val.name3Id = val.kpIndex3Data.id;
};
// 删除按钮 行
const handleDeleteRow = (val) => {
  if (val.index3Id == "" || val.index3Id == null) {
    let index = form.value.dataList.indexOf(val);
    if (index !== -1) {
      form.value.dataList.splice(index, 1);
    }
  } else {
    deleteIndexByIdList({ index3Id: val.index3Id }).then((res) => {
      proxy.$modal.msgSuccess("删除成功");
      getList();
    });
  }
};
// 删除按钮 - 库
const handleDelete = (val) => {
  proxy.$modal
    .confirm("是否确认删除该数据项？")
    .then(function () {
      deleteKpkList({
        kesdId: queryParams.value.kesdId,
      }).then((res) => {
        proxy.$modal.msgSuccess("删除成功");
        appraisalList();
      });
    })
    .catch(() => {});
};

// 选择考评库
const changeKpk = (val) => {
  if (val) {
    queryParams.value.kesdId = val;
    getList();
  } else {
    dataList.value = [];
  }
};

// 获取所有考评库
const appraisalList = () => {
  getAllAppraisal()
    .then((res) => {
      if (res.data && res.data.length > 0) {
        optionData.value = res.data;
        queryParams.value.kesdId = res.data[0].id;
        queryParams.value.name = res.data[0].name;
        isUse.value = res.data[0].isUse;
        getList();
      } else {
        queryParams.value = "";
        dataList.value = [];
      }
    })
    .catch((err) => {});
};
onMounted(() => {
  appraisalList();
});
</script>

<style lang="scss" scoped>
:deep(.el-table).borderTable td.el-table__cell {
  border-bottom: 1px solid #ebeef5 !important;
  border-right: 1px solid #ebeef5 !important;
  .cell {
    height: 68px;
    line-height: 68px;
    .el-form-item {
      position: relative;
      top: 18px;
      .el-input__suffix {
        top: 9px;
      }
    }
  }
}
:deep(.el-table__append-wrapper) {
  text-align: center;
}
.totalButton {
  display: flex;
  align-items: center;
  justify-content: space-around;
  margin: 2px 0 20px;
  .totalPoints {
    font-size: 20px;
    color: #f56c6c;
    font-weight: bold;
  }
}
:deep(.el-table__append-wrapper) {
  text-align: center;
}
</style>
